package com.ruoyi.system.wxService;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.CommonUtil;
import com.ruoyi.system.bo.CommunityMgrUserQueryBo;
import com.ruoyi.system.dto.SendMsgEntity;
import com.ruoyi.system.mapper.CommunityMgrUserMapper;
import com.ruoyi.system.service.impl.ZsyyUserServiceImpl;
import com.ruoyi.system.vo.CommunityMgrUserVo;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WxChatServiceImpl extends BaseWeChatServiceImpl implements WxChatService {
    @Autowired
    public ZsyyUserServiceImpl userService;
    @Autowired
    public CommunityMgrUserMapper userMapper;



    /*
     * @Author wangghua
     * @Description 设备状态发送模板
     * @Date 10:31 2021/11/10
     * @Param [entity]
     * @return void
     **/
	@Override
    public  void sendDeviceMsg(SendMsgEntity entity)  {
    	try {
			// 模板参数
			Map<String, WeChatTemplateMsg> sendMag = new HashMap<String, WeChatTemplateMsg>();
			sendMag.put("first", new WeChatTemplateMsg(entity.getFirstData()));
			sendMag.put("keyword1", new WeChatTemplateMsg(entity.getKeyword1()));
			sendMag.put("keyword2", new WeChatTemplateMsg(entity.getKeyword2()));
			sendMag.put("keyword3", new WeChatTemplateMsg(entity.getKeyword3()));
			sendMag.put("keyword4", new WeChatTemplateMsg(entity.getKeyword4()));
			sendMag.put("keyword5", new WeChatTemplateMsg(entity.getKeyword5()));
			sendMag.put("remark", new WeChatTemplateMsg(entity.getRemark()));
			CommunityMgrUserQueryBo bo = new CommunityMgrUserQueryBo();
			if (!CommonUtil.isEmpty(entity.getCommunityId())){
				bo.setCommunityId(entity.getCommunityId());
			}
			bo.setMsgType(0);//消息类型为设备预警
			List<CommunityMgrUserVo> userList = userMapper.queryList(bo);
			if (userList.size()>0){
				for (CommunityMgrUserVo mgrUserVo:userList) {  //遍历区域管理员
					//发送消息
					this.send(mgrUserVo.getPublicOpenid(), WeixinConstant.DEVICE_STATUS_TEMPLATE_ID, sendMag);
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
    }

	/*
	 * @Author wangghua
	 * @Description 待审核任务发送模板
	 * @Date 10:31 2021/11/10
	 * @Param [entity]
	 * @return void
	 **/
	@Override
    public  void sendReviewMsg(SendMsgEntity entity)  {
    	try {
			// 模板参数
			Map<String, WeChatTemplateMsg> sendMag = new HashMap<String, WeChatTemplateMsg>();
			sendMag.put("first", new WeChatTemplateMsg(entity.getFirstData()));
			sendMag.put("keyword1", new WeChatTemplateMsg(entity.getKeyword1()));
			sendMag.put("keyword2", new WeChatTemplateMsg(entity.getKeyword2()));
			sendMag.put("keyword3", new WeChatTemplateMsg(entity.getKeyword3()));
			sendMag.put("keyword4", new WeChatTemplateMsg(entity.getKeyword4()));
			sendMag.put("keyword5", new WeChatTemplateMsg(entity.getKeyword5()));
			sendMag.put("remark", new WeChatTemplateMsg(entity.getRemark()));
			CommunityMgrUserQueryBo bo = new CommunityMgrUserQueryBo();
			if (!CommonUtil.isEmpty(entity.getCommunityId())){
				bo.setCommunityId(entity.getCommunityId());
			}
			bo.setMsgType(1);//消息类型为设备预警
			List<CommunityMgrUserVo> userList = userMapper.queryList(bo);
			if (userList.size()>0){
				for (CommunityMgrUserVo mgrUserVo:userList) {  //遍历区域管理员
					//发送消息
					this.send(mgrUserVo.getPublicOpenid(), WeixinConstant.REVIEW_WARN_TEMPLATE_ID, sendMag);
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
    }





	/**
	 * 2、发送模版消息
	 * openId     用户Id
	 * templateId 模板Id   测试: "ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY"
	 * data       模板参数
	 * @param data
	 */
	private String send(String openId, String templateId,  Map<String, WeChatTemplateMsg> data) throws Exception {
		String accessToken = weChetAccessToken.getToken();
		String url = WxChatConstant.Url.SEND_URL.replace("ACCESS_TOKEN", accessToken);
		//设置miniProgram 跳转小程序
		WxMpTemplateMessage.MiniProgram miniProgram = new WxMpTemplateMessage.MiniProgram();
		miniProgram.setAppid("wx938e0d5416a3397f");
		//拼接base参数
		Map<String, Object> sendBody = new HashMap<>();
		sendBody.put("touser", openId);                             // openId
		sendBody.put("miniprogram", miniProgram);               // appid
		sendBody.put("topcolor", "#0C0C0C");                    // 黑色
		sendBody.put("data", data);                             // 模板参数
		sendBody.put("template_id", templateId);                // 模板Id
		ResponseEntity<String> forEntity = restTemplate.postForEntity(url, sendBody, String.class);
		return forEntity.getBody();
	}


	/**
	 * 获取所有用户的openID
	 * @return
	 * @throws Exception
	 */
	@Override
	public  String[] getAccountOpenIds()throws Exception {
		String accessToken =weChetAccessToken.getToken();
		OutputStreamWriter out = null;
		BufferedReader br = null;
		String data = "";
		String result = "";
		String[] arrays = new String[0];
		try {
			URL url = new URL("https://api.weixin.qq.com/cgi-bin/user/get?access_token="+accessToken);
			//打开和url之间的连接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			//请求方式
//            conn.setRequestMethod("POST");
			conn.setRequestMethod("GET");

			//设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");

			conn.setDoOutput(true);
			conn.setDoInput(true);
//            conn.setConnectTimeout(6000);
//            conn.setReadTimeout(6000);
			/**
			 * 下面的三句代码，就是调用第三方http接口
			 */
			//获取URLConnection对象对应的输出流
			out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
			//发送请求参数即数据
			out.write(data);
			//flush输出流的缓冲
			out.flush();

			/**
			 * 下面的代码相当于，获取调用第三方http接口后返回的结果
			 */
			//获取URLConnection对象对应的输入流
			InputStream is = conn.getInputStream();
			//构造一个字符流缓存
			br = new BufferedReader(new InputStreamReader(is));
			String str = "";
			while ((str = br.readLine()) != null){
				result += str;
			}
			Map map = JSON.parseObject(result,Map.class);
			//关闭流
			is.close();
			conn.disconnect();
			String data1 = map.get("data").toString();
			Map map1 = JSON.parseObject(data1, Map.class);
			String opens = map1.get("openid").toString();
			String substr = opens.substring(opens.indexOf("[")+1, opens.lastIndexOf("]"));
			arrays = substr.split(",");
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if (out != null){
					out.close();
				}
				if (br != null){
					br.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return arrays;
	}

	/**
	 * 根据openid获取用户的unionid
	 * @param openId
	 * @return
	 * @throws Exception
	 */
	@Override
	public  String getAccountUser(String openId) throws Exception{
		String accessToken =weChetAccessToken.getToken();
		System.out.println("access_token = "+accessToken);
		OutputStreamWriter out = null;
		BufferedReader br = null;
		String data = "";
		String result = "";
		try {
			URL url = new URL("https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accessToken+"&openid="+openId+"&lang=zh_CN");
			//打开和url之间的连接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			//请求方式
//            conn.setRequestMethod("POST");
			conn.setRequestMethod("GET");

			//设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");

			conn.setDoOutput(true);
			conn.setDoInput(true);

			/**
			 * 下面的三句代码，就是调用第三方http接口
			 */
			//获取URLConnection对象对应的输出流
			out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
			//发送请求参数即数据
			out.write(data);
			//flush输出流的缓冲
			out.flush();

			/**
			 * 下面的代码相当于，获取调用第三方http接口后返回的结果
			 */
			//获取URLConnection对象对应的输入流
			InputStream is = conn.getInputStream();
			//构造一个字符流缓存
			br = new BufferedReader(new InputStreamReader(is));
			String str = "";
			while ((str = br.readLine()) != null){
				result += str;
			}
			Map map = JSON.parseObject(result,Map.class);
			//关闭流
			is.close();
			conn.disconnect();
			result = (String) map.get("unionid");
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if (out != null){
					out.close();
				}
				if (br != null){
					br.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

}
